import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerDemo extends StatefulWidget {
  ImagePickerDemo({Key key}) : super(key: key);

  @override
  _ImagePickerDemoState createState() => _ImagePickerDemoState();
}

class _ImagePickerDemoState extends State<ImagePickerDemo> {

  File _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('拍照-选择照片'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            RaisedButton(
              child: Text('拍照'),
              onPressed: _takePhoto
            ),
            RaisedButton(
              child: Text('选择照片'),
              onPressed: _openGallery
            ),
            _buildImage()
          ], 
        ) 
      ) 
    );
  }

  // 拍照
  _takePhoto() async{
    var image = await ImagePicker().getImage(source: ImageSource.camera);

    setState(() {
      this._image = File(image.path);
    });

    // this._uploadImage(image.path);

  }

  // 相册
  _openGallery() async{
    var image = await ImagePicker().getImage(source: ImageSource.gallery);

    setState(() {
      this._image = File(image.path);
    });

    // this._uploadImage(image.path);
  }

  //定义一个组件显示图片
  Widget _buildImage(){
    if(this._image == null) {
      return Text('请选择图片...');
    } else {
      return Image.file(this._image, fit: BoxFit.cover, width: double.infinity, height: 500);
    }
  }

  //上传图片
  _uploadImage(_imageDir) async{
    print('上传图片...');
    FormData formData = new FormData.fromMap({
      "name": "wendux",
      "age": 25,
      "file": await MultipartFile.fromFile(_imageDir, filename: "xx.png")
    });
    print(formData);
    var response = await Dio().post("http://192.168.1.7:9000/gridop/upload", data: formData);
    print(response);

  }

}